<!-- Login.vue -->
<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <img src="@/assets/images/logo.png" alt="Logo" class="logo" />
        <h2>企业信息筛查系统</h2>
      </div>

      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="验证码登录" name="captcha">
          <el-form ref="captchaForm" :model="captchaFormData" :rules="rules" class="login-form">
            <el-form-item prop="phone">
              <el-input v-model="captchaFormData.phone" placeholder="请输入手机号" maxlength="11">
                <template #prepend>
                  <span>中国 +86</span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="captcha">
              <el-input v-model="captchaFormData.captcha" placeholder="请输入验证码">
                <template #append>
                  <el-button :disabled="captchaLoading || captchaCountdown > 0" :loading="captchaLoading" @click="getCaptchaCode">
  {{ captchaCountdown > 0 ? `${captchaCountdown}s` : '获取验证码' }}
</el-button>
                </template>
              </el-input>
            </el-form-item>
            
            <!-- 显示邀请人信息 -->
            <el-form-item v-if="inviterId" label="邀请人">
              <el-input :value="inviterId" disabled></el-input>
            </el-form-item>
            
            <el-button type="primary" class="login-button" :loading="loading" @click="handleCaptchaLogin">
              登录/注册
            </el-button>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="密码登录" name="password">
          <el-form ref="passwordForm" :model="passwordFormData" :rules="rules" class="login-form">
            <el-form-item prop="phone">
              <el-input v-model="passwordFormData.phone" placeholder="请输入手机号" maxlength="11">
                <template #prepend>
                  <span>中国 +86</span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="passwordFormData.password" placeholder="请输入密码" type="password" />
            </el-form-item>
            
            <!-- 显示邀请人信息 -->
            <el-form-item v-if="inviterId" label="邀请人">
              <el-input :value="inviterId" disabled></el-input>
            </el-form-item>
            
            <el-button type="primary" class="login-button" :loading="loading" @click="handlePasswordLogin">
              登录
            </el-button>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div class="footer-links">
        <span>登录即表示您已阅读并同意</span>
        <a href="#" @click.prevent="showAgreement('user')">《用户协议》</a> 和 
        <a href="#" @click.prevent="showAgreement('privacy')">《隐私政策》</a>
      </div>
    </div>
    
    <!-- 协议弹窗 -->
    <agreement-dialog
      v-model="agreementVisible"
      :type="currentAgreementType"
    />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { loginApi, getCaptchaApi } from '@/api/auth'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import AgreementDialog from '@/components/AgreementDialog.vue'

// 接收路由传递的邀请人ID
const props = defineProps({
  inviterId: {
    type: String,
    default: ''
  }
})

// 在 setup 中添加
const userStore = useUserStore()
const router = useRouter()

const activeTab = ref('captcha') // 默认验证码登录
const loading = ref(false)
const captchaCountdown = ref(0)
const captchaForm = ref(null) // 表单引用
const passwordForm = ref(null) // 表单引用

const captchaLoading = ref(false);

const captchaFormData = reactive({
  phone: '',
  captcha: ''
})

const passwordFormData = reactive({
  phone: '',
  password: ''
})

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const startCaptchaCountdown = () => {
  captchaCountdown.value = 60
  const timer = setInterval(() => {
    captchaCountdown.value--
    if (captchaCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const getCaptchaCode = async () => {
  try {
    captchaLoading.value = true;
    // 先验证手机号字段
    await captchaForm.value.validateField('phone');
    
    // 确保phone不为空且格式正确
    if (!captchaFormData.phone || !/^1[3-9]\d{9}$/.test(captchaFormData.phone)) {
      ElMessage.error('请输入正确的手机号');
      return;
    }
    
    // 发送验证码请求
    const response = await getCaptchaApi(captchaFormData.phone);
    
    // 检查响应
    if (response.data && response.data.code === 200) {
      ElMessage.success('验证码已发送');
      startCaptchaCountdown();
    } else {
      ElMessage.error(response.data?.message || '获取验证码失败');
    }
  } catch (error) {
    // 处理验证错误或网络错误
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message);
    } else if (error.message) {
      ElMessage.error(error.message);
    } else {
      ElMessage.error('获取验证码失败，请稍后重试');
    }
    console.error('获取验证码错误:', error);
  } finally {
    captchaLoading.value = false;
  }
};


const handleCaptchaLogin = async () => {
  try {
    loading.value = true
    await captchaForm.value.validate()
    const response = await loginApi({
      phone: captchaFormData.phone,
      captcha: captchaFormData.captcha,
      loginType: 'captcha',
      inviterId: props.inviterId // 传递邀请人ID
    })
    
    if (response.data.code === 201) {
      ElMessage.error(response.data.data)
      return
    }
    
    console.log('登录响应数据:', response.data);
    console.log('Token:', response.data.data.token);
    console.log('用户信息:', response.data.data.user);
    
    userStore.login(response.data.data.token, response.data.data.user)
    
    console.log('登录后状态:', {
      token: userStore.token,
      isAuthenticated: userStore.isAuthenticated,
      localStorage: localStorage.getItem('token')
    });
    
    console.log('firstLogin:', response.data.data.firstLogin);

    if (response.data.data.firstLogin) {
      console.log('首次登录，跳转到设置密码页');
      router.push({ path: '/set-password', query: { phone: captchaFormData.phone } })
    } else {
      console.log('非首次登录，跳转到主页');
      router.push('/main/screening')
    }
  } catch (error) {
    ElMessage.error('登录失败，请重试')
  } finally {
    loading.value = false
  }
}


const handlePasswordLogin = async () => {
  try {
    loading.value = true;
    await passwordForm.value.validate();
    const response = await loginApi({
      phone: passwordFormData.phone,
      password: passwordFormData.password,
      loginType: 'password',
      inviterId: props.inviterId // 传递邀请人ID
    });
    
    if (response.data.code === 201) {
      ElMessage({
        message: response.data.data || '密码错误',
        type: 'error',
        duration: 3000
      });
      return;
    }
    
    // 保存 Token 和用户信息
    userStore.login(response.data.data.token, response.data.data.user)
    router.push('/main/screening');
  } catch (error) {
    // 处理400错误响应
    if (error.response && error.response.status === 400) {
      const errorData = error.response.data;
      ElMessage({
        message: errorData.data || errorData.message || '登录失败',
        type: 'error',
        duration: 3000
      });
    } else {
      ElMessage({
        message: '登录失败，请重试',
        type: 'error',
        duration: 3000
      });
    }
  } finally {
    loading.value = false;
  }
};

// 协议弹窗相关
const agreementVisible = ref(false)
const currentAgreementType = ref('user')

const showAgreement = (type) => {
  currentAgreementType.value = type
  agreementVisible.value = true
}
</script>

<style lang="scss" scoped>
/* 保持原有样式不变 */
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4ecf7 100%);
}

.login-box {
  width: 100%;
  max-width: 400px;
  background: #fff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 60px;
  height: 60px;
  transition: transform 0.3s ease;
  
  &:hover {
    transform: scale(1.05);
  }
}

.login-header h2 {
  font-size: 24px;
  color: #333;
  margin: 10px 0 0;
  background: linear-gradient(45deg, #2b66ff, #4c8dff);
  -webkit-background-clip: text;
  color: transparent;
}

.login-tabs {
  margin-bottom: 20px;
}

.login-form {
  :deep(.el-form-item) {
    margin-bottom: 24px;
  }

  :deep(.el-input__wrapper) {
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;
    
    &:hover, &:focus-within {
      box-shadow: 0 2px 8px rgba(43, 102, 255, 0.1);
    }
  }

  :deep(.el-input-group__prepend) {
    background: #f5f5f5;
    border-right: none;
  }

  :deep(.el-button) {
    &:not(:disabled) {
      background: linear-gradient(45deg, #2b66ff, #4c8dff);
      border: none;
      transition: opacity 0.3s ease;
      color: #ffffff;
      font-weight: 500;
      
      &:hover {
        opacity: 0.9;
      }
    }
    
    &:disabled {
      background: #f5f7fa;
      color: #909399;
      font-weight: 500;
    }
  }
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  background: linear-gradient(45deg, #2b66ff, #4c8dff) !important;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(43, 102, 255, 0.2);
  }
}

.footer-links {
  text-align: center;
  margin-top: 20px;
  font-size: 12px;
  color: #999;
}

.footer-links a {
  color: #2b66ff;
  text-decoration: none;
}

.footer-links a:hover {
  text-decoration: underline;
}
</style>